package edu.bit.water.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.sql.Timestamp;
import java.util.*;

import edu.bit.water.dao.LoginDao;
import edu.bit.water.dto.DateUtils;
import edu.bit.water.entity.Authority;
import edu.bit.water.entity.LoginTime;
import edu.bit.water.service.CompanysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import edu.bit.water.dao.UserDao;
import edu.bit.water.entity.EntityClassifiedStandard;
import edu.bit.water.entity.UserEntity;
import edu.bit.water.web.dto.CarryDto;
import org.springframework.web.context.request.RequestScope;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Controller
@RequestMapping("/user_control")
public class UserController extends BaseController{

	@Autowired
	UserDao userDao;

	@Autowired
	LoginDao loginDao;

	@Autowired
	private CompanysService companysService;

	@Autowired
	private JavaMailSender mailSender;

	@Value("${spring.mail.username}")
	private String mailUserName;

	@Value("${spring.mail.url}")
	private String mailUrl;

	@RequestMapping(value="/login_out", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> doLoginOut() {
		context().userId = -1;
		context().userRole = null;
		String msg = "用户已登出";
		Map<String, Object> result = new HashMap<>();
		result.put("msg", msg);
		result.put("status", "success");
		return result;
	}

	@RequestMapping(value="/dologin", method = RequestMethod.POST)
	@ResponseBody
	public CarryDto<String> dologin(String username, String password) {

		UserEntity user = userDao.findByName(username);

		String msg = "";
		if (user == null) {
			msg = "用户名不存在！";

		}else if (user.getPassword().equals(password)) {
			//在session中保存userId，orgId,以便在其他controller中使用
			context().userId = user.getId();
			context().userRole = user.getRole();
			session.setAttribute("user", user);
			msg = "用户已登录";
			//把登录信息录入登录日志库中
			LoginTime loginTime = new LoginTime();
			loginTime.setUserId(user.getId());
			loginTime.setUserName(user.getName());
			Integer id = loginDao.getMaxId();
			if (id == null) {
				id = 0;
			} else {
				id = id + 1;
			}
			loginTime.setId(id);
			loginTime.setLoginTime(DateUtils.getNowDate());
			loginDao.insertLoginInfo(loginTime);
		} else {
			msg = "用户名密码不匹配";
		}
		return CarryDto.of(msg);
	}
	/**
	 * @return 返回Map 如果查询出错，status为failed,msg为报错信息
	 * 如果查询正确，status为success,如果只有一条数据,返回<result,object>,多条数据返回<results,object>
	 */
	@RequestMapping(value = "/select", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> select() {
		Map<String, Object> modelMap = new HashMap<>();
		List<Map<String, Object>> entityUserlist = userDao.selectEntityUser();
		for (Map<String, Object> stringObjectMap : entityUserlist) {
			List<Integer> roleList = userDao.queryRoleByUserId(stringObjectMap.get("ID").toString());
			stringObjectMap.put("role", roleList);
			String roleName = "";
			for (int i = 0; i < roleList.size(); i++) {
				if (i != roleList.size() - 1) {
					roleName = roleName + userDao.queryRoleName(roleList.get(i)) + ";";
				}
				else {
					roleName = roleName + userDao.queryRoleName(roleList.get(i));
				}
			}
			stringObjectMap.put("ROLE", roleName);
		}
		modelMap.put("rows", entityUserlist);
		return modelMap;
	}

	/**
	 * @return 返回Map 如果查询出错，status为failed,msg为报错信息
	 * 如果查询正确，status为success,如果只有一条数据,返回<result,object>,多条数据返回<results,object>
	 */
	@RequestMapping(value = "/select-by-companyid", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> selectCom(String companyId) {
		Map<String, Object> modelMap = new HashMap<>();
		List<Map<String, Object>> entityUserlist = userDao.selectEntityUserByCom(companyId);
//		List<Authority> entityList = userDao.getAuthority();
//		for (Authority authority : entityList) {
//			authority.setAuthName(authority.getAuthName().replace("水资源/", ""));
//			System.out.println(authority.getAuthName());
//			userDao.setAuthority(authority);
//		}
		for (Map<String, Object> stringObjectMap : entityUserlist) {
			List<Integer> roleList = userDao.queryRoleByUserId(stringObjectMap.get("ID").toString());
			stringObjectMap.put("role", roleList);
			String roleName = "";
			for (int i = 0; i < roleList.size(); i++) {
				if (i != roleList.size() - 1) {
					roleName = roleName + userDao.queryRoleName(roleList.get(i)) + ";";
				}
				else {
					roleName = roleName + userDao.queryRoleName(roleList.get(i));
				}
			}
			stringObjectMap.put("ROLE", roleName);
		}
		modelMap.put("rows", entityUserlist);
		return modelMap;
	}
	@RequestMapping("/insert")
	@ResponseBody
	public Map<String, Object> insert(@RequestBody List<Object> list) {
		UserEntity user = new UserEntity();
		user.setName(list.get(0).toString());
		user.setPassword(list.get(1).toString());
		user.setWorkShop(list.get(3).toString());
		user.setEmail(list.get(4).toString());
		user.setCompanyId(Integer.parseInt(list.get(5).toString()));
		user.setRole(list.get(2).toString());
		Map<String, Object> insertMap = new HashMap<>();
		Map<String, Object> modelMap = new HashMap<>();
		boolean flag = true;
		try {
			userDao.insertUser(user);
		}catch (Exception e) {
			flag = false;

		}
		Integer operator = context().userId;
		Integer userId = userDao.findByName(list.get(0).toString()).getId();
		if(operator == null) {
			modelMap.put("status", "failed");
			return modelMap;
		}
		if(userId == null) {
			modelMap.put("status", "failed");
			modelMap.put("msg", "数据存储失败");
			return modelMap;
		}
		try {
			List<String> list1 = (ArrayList<String>) list.get(2);
			for (String role : list1) {
				userDao.insertRole(userId, role, operator);
			}
		}catch(Exception e) {
			flag = false;
			modelMap.put("msg", "数据保存失败");
		}
		if(flag) {
			modelMap.put("status", "success");
		}else {
			modelMap.put("status", "failed");
		}
		return modelMap;
	}


	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(@RequestBody List<Integer> listId) {
		Map<String, Object> modelMap = new HashMap<>();
		int flag=-1;
		try {
			//使用增强for循环进行删
			for (Integer integer : listId) {
				userDao.deleteRole(integer);
			}
			for(int id : listId) {
				userDao.deleteEntityUser(id);
			}
			flag=1;
		} catch (Exception e) {
			e.printStackTrace();
			flag = 0;
		}
		if (flag == 1) {
			modelMap.put("status", "success");
		} else {
			modelMap.put("status", "failed");
		}
		modelMap.put("msg", "success");
		return modelMap;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Map<String, Object> update(@RequestBody List<Object> list) {
		UserEntity user = new UserEntity();
		user.setId(Integer.parseInt(list.get(0).toString()));
		user.setName(list.get(1).toString());
		user.setPassword(list.get(2).toString());
		user.setWorkShop(list.get(4).toString());
		user.setEmail(list.get(5).toString());
		user.setRole(list.get(3).toString());
		Map<String, Object> modelMap = new HashMap<>();
		boolean flag = true;
		try {
			userDao.updateUser(user);
		}catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		Integer operator = context().userId;
		Integer userId = Integer.parseInt(list.get(0).toString());
		if(operator == null) {
			modelMap.put("status", "failed");
			return modelMap;
		}
		if(userId == null) {
			modelMap.put("status", "failed");
			modelMap.put("msg", "数据存储失败");
			return modelMap;
		}
		try {
			userDao.deleteRole(userId);
			List<String> list1 = (ArrayList<String>) list.get(3);
			for (String role : list1) {
				userDao.insertRole(userId, role, operator);
			}
		}catch(Exception e) {
			flag = false;
			modelMap.put("msg", "数据保存失败");
		}
		if(flag) {
			modelMap.put("status", "success");
		}else {
			modelMap.put("status", "failed");
		}
		return modelMap;
//
//
//
//        //int id = (int) list.remove(0);
//        List<String> lineColumn=new ArrayList<String>();
//        lineColumn.add("USERNAME");
//        lineColumn.add("PASSWORD");
//        lineColumn.add("ROLE");
//        lineColumn.add("WORKSHOP");
//        lineColumn.add("COMPANYID");
//
//        //Map<String, Object> modelMap = new HashMap<>();
//		int length = lineColumn.size();
//		//可變字段在固定字段中間
//		String strSum = "USERNAME=" + "'" + list.remove(0) + "'," +
//				"PASSWORD=" + "'" + list.remove(0) + "'," +
//				"ROLE=" + "'" + list.remove(0) + "'," +
//				"WORKSHOP=" + "'" + list.remove(0) +"',"+
//				"COMPANYID=" +  list.remove(0) ;
//		Map<String, Object> sqlMap = new HashMap<>();
//		sqlMap.put("id", id);
//		sqlMap.put("sql", strSum);
//		try {
//			userDao.updateEntityUser(sqlMap);
//			modelMap.put("status", "success");
//		}catch (DuplicateKeyException e){
//        }
//		return modelMap;
	}
	@RequestMapping(value="/isUser", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> isUser(String username) {
		Map<String, Object> modelMap = new HashMap<>();
		UserEntity user = userDao.findByName(username);
		String msg = "";
		if (user == null) {
			modelMap.put("status","failed");
			modelMap.put("msg","用户名不存在！");

		}else {
			modelMap.put("status","success");
			modelMap.put("rows",user);
			modelMap.put("msg","用户存在");
		}
		return modelMap;
	}

	@RequestMapping("/sendEmail")
	@ResponseBody
	public Map<String, Object> sendEmail(String username, String email) throws MessagingException {
		Map<String, Object> modelMap = new HashMap<>();
		UserEntity user = userDao.findByName(username);
		String Code = String.valueOf(new Random().nextInt(899999) + 100000);//生成短信验证码
		String verifyCode = mailUrl+"?code="+Code;
		Timestamp outDate = new java.sql.Timestamp(System.currentTimeMillis() + 30 * 60 * 1000);// 30分钟后过期
		user.setVerifycode(Code);
		user.setOutdate(outDate);
		userDao.updateUserReset(user);
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("<html><head><title></title></head><body>");
		stringBuilder.append("请勿回复本邮件<br/>");
		stringBuilder.append("点击下面的链接并返回至水资源管理系统，重置密码，本邮件超过30分钟，验证就会失效<br/>");
		stringBuilder.append("您的验证链接是：").append(verifyCode).append("<br/>");
//		stringBuilder.append("您可以复制此验证码并返回至水资源管理系统，以验证您的邮箱。<br/>");
//		stringBuilder.append("请点击链接以验证您的邮箱。<br/>");
//		stringBuilder.append("此验证码只能使用一次，在30分钟内有效。验证成功则自动失效。<br/>");
		stringBuilder.append("如果您没有进行上述操作，请忽略此邮件。");
		MimeMessage mimeMessage = mailSender.createMimeMessage();

		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
		mimeMessageHelper.setFrom(mailUserName);//这里只是设置username 并没有设置host和password，因为host和password在springboot启动创建JavaMailSender实例的时候已经读取了
		mimeMessageHelper.setTo(email);
		mimeMessage.setSubject("邮箱验证-水资源管理系统");
		mimeMessageHelper.setText(stringBuilder.toString(),true);
		mailSender.send(mimeMessage);
		modelMap.put("code",verifyCode);
		modelMap.put("outdate",outDate);
		return modelMap;
	}

	@RequestMapping("/update_new_pwd")
	@ResponseBody
	public Map<String, Object> update_new_pwd(String username, String password) {
		UserEntity user = new UserEntity();
		user.setName(username);
		user.setPassword(password);
		Map<String, Object> modelMap = new HashMap<>();
		try {
			userDao.update_new_pwd(user);
			modelMap.put("status", "success");
			modelMap.put("msg","密码重置成功！请重新登录");
		}catch (Exception e) {
			e.printStackTrace();
			modelMap.put("msg", "数据保存失败");
		}
		return modelMap;
	}

	@RequestMapping(value = "/queryCodeTime", method = RequestMethod.GET)
	@ResponseBody
	private Map<String, Object> queryCodeTime(String code) {
		Map<String, Object> modelMap = new HashMap<>();
		UserEntity user = new UserEntity();
		UserEntity newuser = new UserEntity();
		user.setVerifycode(code);
		newuser = userDao.queryCodeTime(code);
		if(newuser==null){
			modelMap.put("status","failed");
			modelMap.put("msg","链接无效");
		}
		else {
			user.setOutdate(newuser.getOutdate());
			modelMap.put("status","success");
			modelMap.put("msg","成功获取时间");
			modelMap.put("rows", user);
		}
		return modelMap;
	}

	@RequestMapping(value="/reset_and_logout", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> reset_and_logout() {
		int userid= context().userId;
		context().userId = -1;
		context().userRole = null;
		String msg = "用户已登出";
		Map<String, Object> result = new HashMap<>();

		UserEntity user = new UserEntity();
		user=userDao.findById(userid);
		String username=user.getName();

		result.put("username",username);
		result.put("msg", msg);
		result.put("status", "success");
		return result;
	}

}
